package server;

import java.io.IOException;
import java.net.Socket;

import communication.Message;

import exception.ParseException;

public class GMService implements Runnable {
	GamePool gamePool;
	Socket socket;
	boolean finish = false;
	
	public GMService(GamePool gp, Socket s) {
		gamePool = gp;
		socket = s;
	}
	
	public void finish() {
		finish = true;
	}
	
	@Override
	public void run() {
		System.err.println("new gm!\n");
		while(true) {
			try {
				Message msg = gamePool.getGMHandle().receiveMessage();
				switch(msg.getType()) {
					case LEAVE_GAME:
						//gamePool.getPlays().get(msg.getGameId()).sendMessageToPlayers(msg);?
						break;
					case GAME_STATE:
						gamePool.getPlays().get(msg.getGameId().getId()).sendMessageToPlayers(msg);
						if(msg.getGameOver() != null) {
							gamePool.getPlays().remove(msg.getGameId().getId());
							//System.exit(0);
							if(finish)
								return;
						}
						break;
				} 
			} catch (ParseException e) {
				e.printStackTrace();
				System.err.println("koniec!\n");
				return;
			} catch(IOException e) {
				System.err.println("koniec!\n");
				return;
			}
		}
		//socket?
	}
	
}
